package com.hooya.fa.eu.biz.dao.manager.special;

import com.hooya.fa.eu.api.bo.stk.BuyRecordBO;
import com.hooya.fa.eu.api.enums.CountryEnum;
import com.hooya.fa.eu.biz.dao.entity.TempKcjlDaily;
import com.hooya.fa.eu.biz.dao.entity.TempPkpy;
import com.hooya.fa.eu.biz.dao.entity.TempZyjl;
import com.hooya.fa.eu.biz.dao.entity.TradeRecord;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 转运历史数据管理
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/2/27
 * @Version 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class ZyHisDataManager {

    /**
     * 在本仓库和其他仓库不够扣减情况下，去历史仓库找，若有，则做盘亏盘盈记录（针对fba的处理）
     *
     * @param zy               fba转运列表
     * @param fbaHisJcZy       fba历史仓库
     * @param inventoryList    仓库列表
     * @param tradeRecordList  买卖记录集合
     * @param tempZyjlList     转运集合
     * @param metaWarehouseMap 仓库字典
     * @param deleteZyRecord   转运删除集合
     * @param fbaCkCostwayMap
     * @param fbaCkMap
     * @param fbaCkFdsMap
     */
    public void dealWithHisZyData(BuyRecordBO zy, List<BuyRecordBO> fbaHisJcZy,
                                  List<TempKcjlDaily> inventoryList, List<TradeRecord> tradeRecordList,
                                  List<TempZyjl> tempZyjlList, Map<String, String> metaWarehouseMap,
                                  List<BuyRecordBO> deleteZyRecord, List<TempPkpy> pkpyList,
                                  Map<String, Map<String, List<String>>> fbaCkCostwayMap,
                                  Map<String, String> fbaCkMap, Map<String, List<String>> fbaCkFdsMap) {
        Integer cgsl = zy.getCgsl();
        String zcOrigin = metaWarehouseMap.get(zy.getZcck());
        String zlOrigin = metaWarehouseMap.get(zy.getZlck());
        String zcBelongs, zlBelongs;
        if (cgsl > 0) {
            zcBelongs = "FDS-" + zcOrigin;
            zlBelongs = "FDS-" + zlOrigin;
            cgsl = dealWithHisFbaZyDate(zy, fbaHisJcZy, inventoryList, tradeRecordList,
                    tempZyjlList, pkpyList, zcBelongs, zlBelongs, zcOrigin, zlOrigin);
            if (cgsl <= 0) {
                return;
            }
            //costway 历史其他仓库
            for (String origin : CountryEnum.getCountryList()) {
                if (cgsl > 0) {
                    zcBelongs = "COSTWAY-" + origin;
                    zlBelongs = "COSTWAY-" + zlOrigin;
                    cgsl = dealWithHisFbaZyDate(zy, fbaHisJcZy, inventoryList, tradeRecordList,
                            tempZyjlList, pkpyList, zcBelongs, zlBelongs, zcOrigin, zlOrigin);
                }
            }
        }
        //fds与costway历史其他仓库
        if (cgsl > 0) {
            //字典转换货权后缀
            String curCkBelongsSuffix = "";
            //当前belongs货权
            String fbaHisBelongs = "";
            //发货货权地1
            String from1 = "";
            //转到货权地1
            String to1 = "";
            //发货货权地2
            String from2 = "";
            //转到货权地2
            String to2 = "";
            //转入货权地
            String intoBelongs = "";
            //新增买卖（发货1 -> 收货1）
            boolean mm1 = false;
            //新增买卖（发货2 -> 收货2）
            boolean mm2 = false;
            String fdsCk = fbaCkMap.get(zy.getZcck());
            if (StringUtils.isNotBlank(fdsCk)) {
                //FDS
                List<String> fbaFdsCkList = fbaCkFdsMap.get(fdsCk).stream()
                        .filter(l -> !l.equals(zy.getZcck())).collect(Collectors.toList());
                for (String otherCk : fbaFdsCkList) {
                    fbaHisBelongs = "FDS-" + curCkBelongsSuffix;
                    curCkBelongsSuffix = metaWarehouseMap.get(otherCk);
                    from1 = "FDS-" + curCkBelongsSuffix;
                    to1 = "FDS-" + zcOrigin;
                    from2 = to1;
                    to2 = "FDS-" + zlOrigin;
                    intoBelongs = to2;
                    mm1 = !Objects.equals(curCkBelongsSuffix, zcOrigin);
                    mm2 = !Objects.equals(zcOrigin, zlOrigin);
                    cgsl = dealWithOtherHisZyData(zy, fbaHisJcZy, inventoryList,
                            tradeRecordList, tempZyjlList, pkpyList, fbaHisBelongs,
                            zcOrigin, zlOrigin, otherCk, curCkBelongsSuffix, intoBelongs,
                            from1, to1, from2, to2, mm1, mm2);
                }
            }
            if (cgsl > 0) {
                for (String origin : CountryEnum.getCountryList()) {
                    List<String> fbaCostwayCkList = fbaCkCostwayMap.get(fdsCk).get(origin);
                    if (!CollectionUtils.isEmpty(fbaCostwayCkList)) {
                        fbaCostwayCkList = fbaCostwayCkList.stream()
                                .filter(l -> !l.equals(zy.getZcck())).collect(Collectors.toList());
                        for (String otherCk : fbaCostwayCkList) {
                            curCkBelongsSuffix = metaWarehouseMap.get(otherCk);
                            fbaHisBelongs = "COSTWAY-" + otherCk;
                            //CostWay逻辑，判断转出信息
                            from1 = "COSTWAY-" + otherCk;
                            if (zcOrigin.equals(otherCk)) {
                                to1 = from1;
                            } else {
                                to1 = "COSTWAY-" + zcOrigin;
                                mm1 = true;
                            }
                            if (zlOrigin.equals(otherCk)) {
                                from2 = from1;
                                to2 = from2;
                                intoBelongs = to1;
                            } else {
                                from2 = to1;
                                to2 = "COSTWAY-" + zlOrigin;
                                intoBelongs = to2;
                                mm2 = true;
                            }
                            cgsl = dealWithOtherHisZyData(zy, fbaHisJcZy, inventoryList,
                                    tradeRecordList, tempZyjlList, pkpyList, fbaHisBelongs,
                                    zcOrigin, zlOrigin, otherCk, curCkBelongsSuffix, intoBelongs,
                                    from1, to1, from2, to2, mm1, mm2);
                        }
                    }
                }
            }
        }
        if (cgsl > 0) {
            //加到temp_zyjl_delete中去
            BuyRecordBO record = BuyRecordBO.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck())
                    .zlck(zy.getZlck()).cgsl(cgsl).hthm(zy.getHthm()).htrq(zy.getHtrq())
                    .sheetNumber(zy.getSheetNumber()).build();
            deleteZyRecord.add(record);
        }
    }


    private int dealWithHisFbaZyDate(BuyRecordBO zy, List<BuyRecordBO> fbaHisJcZy,
                                     List<TempKcjlDaily> inventoryList, List<TradeRecord> tradeRecordList,
                                     List<TempZyjl> tempZyjlList, List<TempPkpy> pkpyList, String zcBelongs,
                                     String zlBelongs, String zcOrigin, String zlOrigin) {
        //增加盘亏盘盈
        if (fbaHisJcZy.stream().noneMatch(l -> l.getCpbh().equals(zy.getCpbh()) &&
                l.getPlace().equals(zy.getZcck()) && l.getBelongs().equals(zcBelongs))) {
            return zy.getCgsl();
        }
        TempPkpy pkpy = TempPkpy.builder().cpbh(zy.getCpbh()).place(zy.getZcck())
                .sl(-zy.getCgsl()).belongs(zcBelongs).date(zy.getHtrq()).build();
        pkpyList.add(pkpy);
        //转入新增
        if (inventoryList.stream().anyMatch(l -> l.getCpbh().equals(zy.getCpbh()) &&
                l.getPlace().equals(zy.getZlck()) && l.getBelongs().equals(zlBelongs))) {
            inventoryList.stream().filter(l ->
                            l.getCpbh().equals(zy.getCpbh()) &&
                                    l.getPlace().equals(zy.getZlck()) &&
                                    l.getBelongs().equals(zlBelongs))
                    .forEach(l -> l.setSl(l.getSl() + zy.getCgsl()));
        } else {
            TempKcjlDaily kcjlDaily = TempKcjlDaily.builder().belongs(zlBelongs).place(zy.getZlck())
                    .cpbh(zy.getCpbh()).sl(zy.getCgsl()).build();
            inventoryList.add(kcjlDaily);
        }
        TempZyjl zyjl = TempZyjl.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck()).zlck(zy.getZlck())
                .cgsl(zy.getCgsl()).hthm(zy.getHthm()).htrq(zy.getHtrq()).frombelongs(zcBelongs)
                .tobelongs(zlBelongs).fromcountry(zcOrigin).tocountry(zlOrigin)
                .sheetnumber(zy.getSheetNumber()).build();
        tempZyjlList.add(zyjl);
        if (!Objects.equals(zcOrigin, zlOrigin)) {
            //新增买卖记录(company小写)
            TradeRecord tradeRecord = TradeRecord.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck())
                    .zlck(zy.getZlck()).mmsl(zy.getCgsl()).fromcompany(zcBelongs.toLowerCase())
                    .tocompany(zlBelongs.toLowerCase()).fromcountry(zcOrigin).tocountry(zlOrigin)
                    .type("转运").zyhthm(zy.getHthm()).date(zy.getHtrq()).build();
            tradeRecordList.add(tradeRecord);
        }
        return 0;
    }


    private int dealWithOtherHisZyData(BuyRecordBO zy, List<BuyRecordBO> fbaHisJcZy, List<TempKcjlDaily> inventoryList,
                                       List<TradeRecord> tradeRecordList, List<TempZyjl> tempZyjlList,
                                       List<TempPkpy> pkpyList, String fbaHisBelongs, String zcOrigin, String zlOrigin,
                                       String otherCk, String curCkBelongsSuffix, String intoBelongs,
                                       String from1, String to1, String from2, String to2, boolean addMm1,
                                       boolean addMm2) {
        if (fbaHisJcZy.stream().noneMatch(l -> l.getCpbh().equals(zy.getCpbh()) &&
                l.getPlace().equals(otherCk) && l.getBelongs().equals(fbaHisBelongs))) {
            return zy.getCgsl();
        }
        TempPkpy pkpy = TempPkpy.builder().cpbh(zy.getCpbh()).place(otherCk).sl(-zy.getCgsl())
                .belongs(fbaHisBelongs).date(zy.getHtrq()).build();
        pkpyList.add(pkpy);
        //转入新增
        if (inventoryList.stream().anyMatch(l -> l.getCpbh().equals(zy.getCpbh()) &&
                l.getPlace().equals(zy.getZlck()) && l.getBelongs().equals(intoBelongs))) {
            inventoryList.stream().filter(l ->
                            l.getCpbh().equals(zy.getCpbh()) &&
                                    l.getPlace().equals(zy.getZlck()) &&
                                    l.getBelongs().equals(intoBelongs))
                    .forEach(l -> l.setSl(l.getSl() + zy.getCgsl()));
        } else {
            TempKcjlDaily kcjlDaily = TempKcjlDaily.builder().belongs(to2)
                    .place(zy.getZlck()).cpbh(zy.getCpbh()).sl(zy.getCgsl()).build();
            inventoryList.add(kcjlDaily);
        }
        //转运
        TempZyjl otherToZc = TempZyjl.builder().cpbh(zy.getCpbh()).zcck(otherCk).zlck(zy.getZcck())
                .cgsl(zy.getCgsl()).hthm(zy.getHthm()).htrq(zy.getHtrq()).frombelongs(from1)
                .tobelongs(to1).fromcountry(curCkBelongsSuffix).tocountry(zcOrigin)
                .sheetnumber(zy.getSheetNumber()).build();
        tempZyjlList.add(otherToZc);
        TempZyjl zcToZl = TempZyjl.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck()).zlck(zy.getZlck())
                .cgsl(zy.getCgsl()).hthm(zy.getHthm()).htrq(zy.getHtrq()).frombelongs(from2)
                .tobelongs(to2).fromcountry(zcOrigin).tocountry(zlOrigin)
                .sheetnumber(zy.getSheetNumber()).build();
        tempZyjlList.add(zcToZl);
        if (addMm1) {
            //新增买卖记录(company小写)
            TradeRecord tradeRecord = TradeRecord.builder().cpbh(zy.getCpbh()).zcck(otherCk)
                    .zlck(zy.getZcck()).mmsl(zy.getCgsl()).fromcompany(from1.toLowerCase())
                    .tocompany(to1.toLowerCase()).fromcountry(zcOrigin).tocountry(zlOrigin)
                    .type("转运").zyhthm(zy.getHthm()).date(zy.getHtrq()).build();
            tradeRecordList.add(tradeRecord);
        }
        if (addMm2) {
            //新增买卖记录(company小写)
            TradeRecord tradeRecord = TradeRecord.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck())
                    .zlck(zy.getZlck()).mmsl(zy.getCgsl()).fromcompany(from2.toLowerCase())
                    .tocompany(to2.toLowerCase()).fromcountry(zcOrigin).tocountry(zlOrigin)
                    .type("转运").zyhthm(zy.getHthm()).date(zy.getHtrq()).build();
            tradeRecordList.add(tradeRecord);
        }
        return 0;
    }

}
